package cn.sql_session.utils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * 类简介: 扫描文件实用程序
 *
 * @Author: ShangGuan
 * @Time: 2024/05/22
 **/
public class ScanFileUtils {
    /**
     * 扫描指定包下的-> 扫描 XML 文件,  scanXmlFiles("mybatis/mapper/")扫描 className=mybatis/mapper/下面的xml文件
     *
     * @param packageName 软件包名称
     * @return {@link List }<{@link String }>
     * @throws IOException io异常
     **/
    public static List<String> scanXmlFiles(String packageName) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<String> xmlFiles = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            xmlFiles.addAll(findXmlFiles(resource, packageName));
        }
        return xmlFiles;
    }

    /**
     * 查找 XML 文件
     *
     * @param directory   目录
     * @param packageName 软件包名称
     * @return {@link List }<{@link String }>
     **/
    private static List<String> findXmlFiles(URL directory, String packageName) {
        List<String> xmlFiles = new ArrayList<>();
        File directoryFile = new File(directory.getFile());
        if (directoryFile.exists() && directoryFile.isDirectory()) {
            File[] files = directoryFile.listFiles((dir, name) -> name.endsWith(".xml"));
            if (files != null) {
                for (File file : files) {
                    xmlFiles.add(packageName  + file.getName());
                }
            }
        }
        return xmlFiles;
    }
}
